# -*- coding: utf-8 -*-
from common import logable, trace_method, NDW_ERROR, NDW_DEBUG

__author__ = 'sysprog'

@logable
class ChecksumChecker(object):
    def __init__(self):
        self.cs_result = []

    @trace_method
    def load_from_string(self, signatures):
        import hashlib
        import os

        for line in signatures.split("\n"):
            checksum, filename = line.split()
            if os.path.exists(filename):
                with file(filename, "r") as testfile:
                    ftext = testfile.read()
                    sha256chiper = hashlib.sha256()
                    sha256chiper.update(ftext)
                    sha256sum = sha256chiper.hexdigest()
                    is_equal = checksum == sha256sum
                    self.log(NDW_DEBUG, "file %s hashsum is%sequal to expected", filename, is_equal and " " or " not ")
                    if not is_equal:
                        self.log(NDW_DEBUG, "expected hashsum is '%s'", checksum)
                        self.log(NDW_DEBUG, "actual   hashsum is '%s'", sha256sum)
                    self.cs_result.append((True, filename, checksum == sha256sum, checksum, sha256sum))
            else:
                self.log(NDW_DEBUG, "file '%s' doesn't exists", filename)
                self.cs_result.append((False, filename, False, checksum, 0))